package com.jnu.myAccount.menu.home;


import static android.app.Activity.RESULT_OK;

import static com.jnu.myAccount.MyTextInputWatcher.getStandardFloatString;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.jnu.myAccount.R;
import com.jnu.myAccount.activity.DetailActivity;
import com.jnu.myAccount.databinding.BalancePopupwindowLayoutBinding;
import com.jnu.myAccount.databinding.FragmentHomeBinding;
import com.jnu.myAccount.activity.EditActivity;
import com.jnu.myAccount.record.AccountFundInfo;
import com.jnu.myAccount.record.DataPackage;
import com.jnu.myAccount.record.FundAdapter;
import com.jnu.myAccount.record.Record;

import java.util.List;
import java.util.Map;
import java.util.Objects;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private FragmentHomeBinding fragmentHomeBinding;
    private RecyclerView recycleView;
    private HomeFragment.DateRecycleAdapter DateRecycleAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private PopupWindow setBalanceWindow;
    private BalancePopupwindowLayoutBinding balancePopupwindowLayoutBinding;
    private EditText editTextPopupInputBudget;
    private DataPackage dataPackage;

    private Intent intent;
    private ActivityResultLauncher<Intent> intentSenderRequestActivityResultLauncher;

    /* 1. 配置recyclerview实现账目浏览功能
     ··2. 配置swipeRefreshLayout实现刷新数据功能
     ··3. 监听余额预算的相关事件
     ··4. 监视是否设置了本月预算实现显示预算功能
     ··5. 设置本月收入、支出
     ··6. 监听浮动按钮点击事件实现MainActivity跳转至EditActivity功能 */
    //MainActivity => EditActivity
    @SuppressLint("NotifyDataSetChanged")
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        fragmentHomeBinding = FragmentHomeBinding.inflate(inflater, container, false);
        dataPackage = DataPackage.Instance();
        View root = fragmentHomeBinding.getRoot();

        //1. 配置recyclerview实现账目浏览功能
        //------------------------------------------------------------------------------------------
        recycleView = fragmentHomeBinding.homeRecycleView;
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(root.getContext(), LinearLayoutManager.VERTICAL, false);
        recycleView.setLayoutManager(linearLayoutManager);
        DateRecycleAdapter = new DateRecycleAdapter();
        recycleView.setAdapter(DateRecycleAdapter);
        //------------------------------------------------------------------------------------------

        //2. 配置swipeRefreshLayout实现刷新数据功能
        //------------------------------------------------------------------------------------------
        swipeRefreshLayout = fragmentHomeBinding.swipeLayout;
        swipeRefreshLayout.setColorSchemeColors(Color.RED);
        swipeRefreshLayout.setOnRefreshListener(() -> {
            homeViewModel.loadData();
            DateRecycleAdapter.notifyDataSetChanged();
            swipeRefreshLayout.setRefreshing(false);
        });
        //------------------------------------------------------------------------------------------

        //3. 监听余额预算相关的事件
        //------------------------------------------------------------------------------------------
        balancePopupwindowLayoutBinding = BalancePopupwindowLayoutBinding.inflate
                (LayoutInflater.from(requireActivity()),null,false);
        setBalanceWindow = new PopupWindow(balancePopupwindowLayoutBinding.getRoot(),
                ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        editTextPopupInputBudget = balancePopupwindowLayoutBinding.inputBudget;
        setBalanceWindow.setFocusable(true);
        editTextPopupInputBudget.setFocusable(true);

        //监听点击余额的事件，弹出窗口
        fragmentHomeBinding.layoutBalance.setOnClickListener(v -> {
            //初始化预算设置窗口的位置，显示的日期范围、默认预算
            editTextPopupInputBudget.setText(homeViewModel.getBudgetBalanceString());
            balancePopupwindowLayoutBinding.homePopupSubTitle.setText(homeViewModel.getDateRangeString());
            setBalanceWindow.showAtLocation(v, Gravity.CENTER,0,0);
            editTextPopupInputBudget.requestFocus();
        });

        //监听关闭按钮点击事件
        balancePopupwindowLayoutBinding.homePopupCloseButton.setOnClickListener(v -> setBalanceWindow.dismiss());

        //监听确定按钮点击事件，将余额保存到数据模块
        balancePopupwindowLayoutBinding.homePopupOkButton.setOnClickListener(v -> {
            homeViewModel.setBalance(
                    editTextPopupInputBudget.getText().toString());
            setBalanceWindow.dismiss();
        });

        //4. 监视是否设置了本月预算判断需要显示预算还是余额
        homeViewModel.getBudget().observe(getViewLifecycleOwner(), v -> {
            fragmentHomeBinding.monthBudgetBalanceTitle.
                    setText(homeViewModel.getBudgetBalanceTitleString());
            fragmentHomeBinding.monthBudgetBalanceValue.
                    setText(homeViewModel.getBudgetBalanceString());
        });
        //------------------------------------------------------------------------------------------

        //5. 设置本月收入、支出
        homeViewModel.getInText().observe(getViewLifecycleOwner(),
                s -> fragmentHomeBinding.monthBudgetInputValue.setText(s));
        homeViewModel.getOutText().observe(getViewLifecycleOwner(),
                s -> fragmentHomeBinding.monthBudgetOutputValue.setText(s));

        //6. MainActivity => EditActivity
        //------------------------------------------------------------------------------------------
        intentSenderRequestActivityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(), this::onActivityResult );
        intent = new Intent(this.getContext(), EditActivity.class);
        dataPackage.setNeedModify(false);
        fragmentHomeBinding.editButton.setOnClickListener(view ->  {
            intentSenderRequestActivityResultLauncher.launch(intent);
        });
        //------------------------------------------------------------------------------------------

        return root;
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onStart() {
        super.onStart();
        //加载数据
        homeViewModel.loadData();
        //刷新recyclerview
        DateRecycleAdapter.notifyDataSetChanged();
    }

    //Activity结束执行的函数
    @SuppressLint("NotifyDataSetChanged")
    private void onActivityResult(ActivityResult activityResult)
    {
        if(activityResult.getResultCode()==RESULT_OK)
        {
            swipeRefreshLayout.setRefreshing(true);
            homeViewModel.syncInDateInfo();
            homeViewModel.Refreshing();
            DateRecycleAdapter.notifyDataSetChanged();
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    public class DateRecycleAdapter extends RecyclerView.Adapter<HomeFragment.DateRecycleAdapter.DateViewHolder>{
        @NonNull
        @Override
        public DateViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.layout_date_record,parent,false);
            return new DateViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull DateViewHolder holder, int position) {
            //获取日期和单位流水信息列表
            String date = homeViewModel.getDate(position);
            List<Record> inflows = Objects.requireNonNull(homeViewModel.getRecordMap().get(date));

            //初始化布局
            holder.getDate().setText(date);
            holder.getIn().setText(String.valueOf(homeViewModel.getTotalIn(date)));
            holder.getOut().setText(String.valueOf(homeViewModel.getTotalOut(date)));

            //设置适配器
            RecordRecycleAdapter recordRecycleAdapter = new RecordRecycleAdapter(inflows,date);
            holder.getInnerRecyclerView().setAdapter(recordRecycleAdapter);
        }

        @Override
        public int getItemCount() {
            return homeViewModel.getRecordMap().size();
        }

        public class DateViewHolder extends RecyclerView.ViewHolder {
            private final TextView date;
            private final TextView in;
            private final TextView out;
            private final RecyclerView innerRecyclerView;
            public DateViewHolder(@NonNull View itemView) {
                super(itemView);
                date = itemView.findViewById(R.id.head_addition_date_value);
                in = itemView.findViewById(R.id.head_addition_in_value);
                out = itemView.findViewById(R.id.head_addition_out_value);
                innerRecyclerView = itemView.findViewById(R.id.home_inner_recycleView);

                //为内部recyclerview设置线性布局管理器
                LinearLayoutManager innerLinearLayoutManager = new LinearLayoutManager(itemView.getContext(),LinearLayoutManager.VERTICAL,
                        false);
                innerRecyclerView.setLayoutManager(innerLinearLayoutManager);
            }

            public TextView getDate() {
                return date;
            }

            public TextView getIn() {
                return in;
            }

            public TextView getOut() {
                return out;
            }

            public RecyclerView getInnerRecyclerView() {
                return innerRecyclerView;
            }
        }

        public class RecordRecycleAdapter extends RecyclerView.Adapter<RecordRecycleAdapter.RecordViewHolder>
        {
            private final List<Record> recordList;
            private final String date;

            public RecordRecycleAdapter(List<Record> list, String date)
            {
                super();
                recordList =list;
                this.date=date;
            }

            @NonNull
            @Override
            public RecordViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.layout_item,parent,false);
                return new RecordViewHolder(view);
            }

            @Override
            public void onBindViewHolder(@NonNull RecordViewHolder holder, int position) {
                if (recordList.get(position).isInOrOutValue())
                    holder.fundFlow.setText(getStandardFloatString(recordList.get(position).getFundValue()));
                else{
                    holder.fundFlow.setText(getStandardFloatString( - recordList.get(position).getFundValue()));
                    holder.fundFlow.setTextColor(Color.RED);
                }
                holder.imageView.setImageResource(recordList.get(position).getIconResource());
                holder.headKind.setText(recordList.get(position).getTypeString());
                holder.fundKind.setText(recordList.get(position).getAccount());
                holder.date=date;
            }

            @Override
            public int getItemCount() {
                return recordList.size();
            }

            public String getDate() {
                return date;
            }

            public class RecordViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener
            {
                public final ImageView imageView;
                public final TextView headKind;
                public final TextView fundKind;
                public final TextView fundFlow;
                public String date;

                public RecordViewHolder(@NonNull View itemView) {
                    super(itemView);
                    imageView = itemView.findViewById(R.id.item_img);
                    headKind = itemView.findViewById(R.id.item_head);
                    fundKind = itemView.findViewById(R.id.item_subtitle);
                    fundFlow = itemView.findViewById(R.id.item_funds_flow);

                    //设置上下文菜单监听器
                    itemView.setOnCreateContextMenuListener(this);
                }

                @SuppressLint("NotifyDataSetChanged")
                public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                    MenuItem menuItemDelete = menu.add(Menu.NONE,1,1, R.string.string_delete);
                    MenuItem menuItemDetail = menu.add(Menu.NONE,2,2, R.string.string_detail);
                    MenuItem menuItemModify = menu.add(Menu.NONE,3,3, R.string.string_modify);
                    MenuItem menuItemRefresh = menu.add(Menu.NONE,4,4, R.string.string_refresh);

                    //监听删除选项
                    menuItemDelete.setOnMenuItemClickListener(item -> {
                        int innerPosition = getAdapterPosition();
                        homeViewModel.deleteRecord(date,innerPosition);
                        homeViewModel.loadData();
                        DateRecycleAdapter.notifyDataSetChanged();
                        return true;
                    });

                    //监听详情选项
                    menuItemDetail.setOnMenuItemClickListener(item -> {
                        Record recordToShow = recordList.get(getAdapterPosition());
                        Intent detailIntent=new Intent(getContext(), DetailActivity.class);
                        float balance = 0;
                        AccountFundInfo accountFundInfo = dataPackage.getAccountFundInfoMap().get(recordToShow.getAccount());
                        Map<String, FundAdapter> fundInfoMap = accountFundInfo.getFundInfoMap();
                        List<String> dateList = dataPackage.getDateList();
                        for (int i = 0; i<dateList.size();i++){
                            String date = dateList.get(i);
                            FundAdapter fundAdapter = fundInfoMap.get(date);
                            List<Record> recordList = fundAdapter.getRecordList();
                            for (int j =0; j < recordList.size();j++){
                                Record record = recordList.get(j);
                                if (record.isInOrOutValue()){
                                    balance+=record.getFundValue();
                                } else balance-=record.getFundValue();
                            }
                        }

                        detailIntent.putExtra("fundValue",recordToShow.getFundValue());
                        detailIntent.putExtra("type",recordToShow.getTypeString());
                        detailIntent.putExtra("inout",recordToShow.isInOrOutValue());
                        detailIntent.putExtra("account",recordToShow.getAccount());
                        detailIntent.putExtra("balance",balance);

                        //开启通信
                        intentSenderRequestActivityResultLauncher.launch(detailIntent);
                        return true;

                    });

                    //监听修改选项
                    menuItemModify.setOnMenuItemClickListener(item -> {
                        Record recordNeedToModify = recordList.get(getAdapterPosition());
                        dataPackage.setRecordNeedToModify(recordNeedToModify);
                        dataPackage.setHomeViewModel(homeViewModel);
                        dataPackage.setModifyDate(date);
                        dataPackage.setModifyPosition(getAdapterPosition());
                        dataPackage.setNeedModify(true);
                        intent.putExtra("tab",0);
                        intentSenderRequestActivityResultLauncher.launch(intent);
                        return true;
                    });

                    //监听刷新选项
                    menuItemRefresh.setOnMenuItemClickListener(item -> {
                        homeViewModel.loadData();
                        DateRecycleAdapter.notifyDataSetChanged();
                        return true;
                    });
                }

            }
        }
    }
}